<script setup>
import { ref, onMounted, onUnmounted, watch, h } from "vue";
import {
  Boxes,
  Clock,
  Trophy,
  Star,
  CheckCircle,
  RotateCcw,
} from "lucide-vue-next";
import { useI18n } from "vue-i18n";

const { t } = useI18n();

const props = defineProps({
  onComplete: Function,
});

const stage = ref("instructions"); // 'instructions', 'test', 'results'
const currentPattern = ref(0);
const patterns = ref([]);
const responses = ref([]);
const timeLeft = ref(600); // 10 minutes
const startTime = ref(0);
const score = ref(0);
const showFeedback = ref(false);
const feedbackCorrect = ref(false);

const TOTAL_PATTERNS = 15;

// Shape rendering logic as a functional component
const ShapeRenderer = (props) => {
  const { element, baseSize = 40 } = props;

  if (!element) {
    return h("div", {
      style: {
        width: `${baseSize}px`,
        height: `${baseSize}px`,
        backgroundColor: "#f1f5f9",
        border: "1px dashed #cbd5e1",
        borderRadius: "4px",
      },
    });
  }

  const {
    shape,
    color,
    filled = true,
    rotation = 0,
    size = "medium",
  } = element;
  const sizeMultiplier = size === "small" ? 0.4 : size === "large" ? 1.8 : 1.0;
  const actualSize = Math.round(baseSize * sizeMultiplier);

  const colorClass = {
    red: filled ? "#ef4444" : "transparent",
    blue: filled ? "#3b82f6" : "transparent",
    green: filled ? "#10b981" : "transparent",
    yellow: filled ? "#f59e0b" : "transparent",
    purple: filled ? "#8b5cf6" : "transparent",
    orange: filled ? "#f97316" : "transparent",
    pink: filled ? "#ec4899" : "transparent",
    black: filled ? "#1f2937" : "transparent",
  };

  const strokeColor = {
    red: "#ef4444",
    blue: "#3b82f6",
    green: "#10b981",
    yellow: "#f59e0b",
    purple: "#8b5cf6",
    orange: "#f97316",
    pink: "#ec4899",
    black: "#1f2937",
  };

  const baseProps = {
    width: actualSize,
    height: actualSize,
    viewBox: `0 0 ${actualSize} ${actualSize}`,
    fill: colorClass[color] || "#64748b",
    stroke: strokeColor[color] || "#64748b",
    strokeWidth: filled ? 0 : 2,
    style: {
      transform: `rotate(${rotation || 0}deg)`,
      display: "block",
    },
  };

  const padding = 2;
  const innerSize = actualSize - padding * 2;

  switch (shape) {
    case "circle":
      return h("svg", baseProps, [
        h("circle", {
          cx: actualSize / 2,
          cy: actualSize / 2,
          r: innerSize / 2,
        }),
      ]);
    case "square":
      return h("svg", baseProps, [
        h("rect", {
          x: padding,
          y: padding,
          width: innerSize,
          height: innerSize,
        }),
      ]);
    case "triangle":
      return h("svg", baseProps, [
        h("polygon", {
          points: `${actualSize / 2},${padding} ${padding},${
            actualSize - padding
          } ${actualSize - padding},${actualSize - padding}`,
        }),
      ]);
    case "diamond":
      return h("svg", baseProps, [
        h("polygon", {
          points: `${actualSize / 2},${padding} ${actualSize - padding},${
            actualSize / 2
          } ${actualSize / 2},${actualSize - padding} ${padding},${
            actualSize / 2
          }`,
        }),
      ]);
    case "star":
      const cx = actualSize / 2;
      const cy = actualSize / 2;
      const r1 = innerSize / 2;
      const r2 = r1 * 0.4;
      let points = "";
      for (let i = 0; i < 10; i++) {
        const r = i % 2 === 0 ? r1 : r2;
        const angle = (i * Math.PI) / 5;
        const x = cx + r * Math.cos(angle - Math.PI / 2);
        const y = cy + r * Math.sin(angle - Math.PI / 2);
        points += `${x},${y} `;
      }
      return h("svg", baseProps, [h("polygon", { points: points.trim() })]);
    case "hexagon":
      const hexCx = actualSize / 2;
      const hexCy = actualSize / 2;
      const hexR = innerSize / 2;
      const hexPoints = Array.from({ length: 6 }, (_, i) => {
        const angle = (i * Math.PI) / 3;
        const x = hexCx + hexR * Math.cos(angle);
        const y = hexCy + hexR * Math.sin(angle);
        return `${x},${y}`;
      }).join(" ");
      return h("svg", baseProps, [h("polygon", { points: hexPoints })]);
    default:
      return h(
        "div",
        {
          style: {
            width: `${actualSize}px`,
            height: `${actualSize}px`,
            backgroundColor: "#f1f5f9",
            border: "1px solid #e2e8f0",
            borderRadius: "4px",
            display: "flex",
            alignItems: "center",
            justifyContent: "center",
            fontSize: "10px",
            color: "#64748b",
          },
        },
        "?"
      );
  }
};

const generatePatterns = () => {
  const newPatterns = [];
  let patternId = 1;

  const baseDistribution = [4, 3, 3, 2, 2, 1];
  let distribution = [...baseDistribution];
  const totalAdjustment = Math.floor(Math.random() * 3) - 1;
  if (totalAdjustment !== 0) {
    const randomIndex1 = Math.floor(Math.random() * distribution.length);
    let randomIndex2 = Math.floor(Math.random() * distribution.length);
    while (randomIndex2 === randomIndex1) {
      randomIndex2 = Math.floor(Math.random() * distribution.length);
    }
    if (distribution[randomIndex1] > 1) {
      distribution[randomIndex1] += totalAdjustment;
      distribution[randomIndex2] -= totalAdjustment;
    }
  }

  for (let i = 0; i < distribution[0]; i++)
    newPatterns.push(generateSequencePattern(patternId++));
  for (let i = 0; i < distribution[1]; i++)
    newPatterns.push(generateMatrixPattern(patternId++));
  for (let i = 0; i < distribution[2]; i++)
    newPatterns.push(generateRotationPattern(patternId++));
  for (let i = 0; i < distribution[3]; i++)
    newPatterns.push(generateColorSequencePattern(patternId++));
  for (let i = 0; i < distribution[4]; i++)
    newPatterns.push(generateSizeProgressionPattern(patternId++));
  for (let i = 0; i < distribution[5]; i++)
    newPatterns.push(generateShapePattern(patternId++));

  if (newPatterns.length < TOTAL_PATTERNS) {
    const remaining = TOTAL_PATTERNS - newPatterns.length;
    for (let i = 0; i < remaining; i++) {
      newPatterns.push(generateComplexPattern(patternId++));
    }
  }

  for (let i = newPatterns.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    [newPatterns[i], newPatterns[j]] = [newPatterns[j], newPatterns[i]];
  }

  return newPatterns.slice(0, TOTAL_PATTERNS);
};

const generateSequencePattern = (id) => {
  const shapes = ["circle", "square", "triangle", "diamond", "star", "hexagon"];
  const colors = ["red", "blue", "green", "yellow", "purple", "orange", "pink"];
  const patternTypes = [
    "shape_cycle",
    "color_cycle",
    "alternating",
    "growing_cycle",
    "mixed_attribute",
  ];
  const patternType =
    patternTypes[Math.floor(Math.random() * patternTypes.length)];

  if (patternType === "shape_cycle") {
    const cycleLength = Math.floor(Math.random() * 3) + 3;
    const selectedShapes = shapes.slice(0, cycleLength);
    const elements = [];
    const color = colors[Math.floor(Math.random() * colors.length)];
    for (let i = 0; i < 5; i++) {
      elements.push({
        shape: selectedShapes[i % cycleLength],
        color,
        size: "medium",
        filled: true,
      });
    }
    const nextShape = selectedShapes[5 % cycleLength];
    const options = [
      [{ shape: nextShape, color, size: "medium", filled: true }],
      [
        {
          shape: selectedShapes[(5 + 1) % cycleLength],
          color,
          size: "medium",
          filled: true,
        },
      ],
      [
        {
          shape: selectedShapes[(5 + 2) % cycleLength],
          color,
          size: "medium",
          filled: true,
        },
      ],
      [
        {
          shape: shapes[shapes.length - 1],
          color,
          size: "medium",
          filled: true,
        },
      ],
    ];
    return {
      id,
      type: "sequence",
      elements,
      question: [{ shape: nextShape, color, size: "medium", filled: true }],
      options,
      correct: 0,
      difficulty: "easy",
      description: t(
        "patternRecognitionTest.descriptions.sequence_shape_cycle",
        { cycleLength }
      ),
    };
  } else if (patternType === "color_cycle") {
    const shape = shapes[Math.floor(Math.random() * shapes.length)];
    const cycleLength = Math.floor(Math.random() * 3) + 3;
    const selectedColors = colors.slice(0, cycleLength);
    const elements = [];
    for (let i = 0; i < 5; i++) {
      elements.push({
        shape,
        color: selectedColors[i % cycleLength],
        size: "medium",
        filled: true,
      });
    }
    const nextColor = selectedColors[5 % cycleLength];
    const options = [
      [{ shape, color: nextColor, size: "medium", filled: true }],
      [
        {
          shape,
          color: selectedColors[(5 + 1) % cycleLength],
          size: "medium",
          filled: true,
        },
      ],
      [
        {
          shape,
          color: selectedColors[(5 + 2) % cycleLength],
          size: "medium",
          filled: true,
        },
      ],
      [
        {
          shape,
          color: colors[colors.length - 1],
          size: "medium",
          filled: true,
        },
      ],
    ];
    return {
      id,
      type: "sequence",
      elements,
      question: [{ shape, color: nextColor, size: "medium", filled: true }],
      options,
      correct: 0,
      difficulty: "medium",
      description: t(
        "patternRecognitionTest.descriptions.sequence_color_cycle",
        { cycleLength }
      ),
    };
  } else {
    // Fallback to simple alternating
    const shape1 = shapes[Math.floor(Math.random() * shapes.length)];
    let shape2 = shapes[Math.floor(Math.random() * shapes.length)];
    while (shape2 === shape1)
      shape2 = shapes[Math.floor(Math.random() * shapes.length)];
    const color1 = colors[Math.floor(Math.random() * colors.length)];
    let color2 = colors[Math.floor(Math.random() * colors.length)];
    while (color2 === color1)
      color2 = colors[Math.floor(Math.random() * colors.length)];
    const elements = [
      { shape: shape1, color: color1, size: "medium", filled: true },
      { shape: shape2, color: color2, size: "medium", filled: true },
      { shape: shape1, color: color1, size: "medium", filled: true },
      { shape: shape2, color: color2, size: "medium", filled: true },
      { shape: shape1, color: color1, size: "medium", filled: true },
    ];
    const nextElement = {
      shape: shape2,
      color: color2,
      size: "medium",
      filled: true,
    };
    const options = [
      [nextElement],
      [{ shape: shape1, color: color1, size: "medium", filled: true }],
      [{ shape: shape1, color: color2, size: "medium", filled: true }],
      [{ shape: shape2, color: color1, size: "medium", filled: true }],
    ];
    return {
      id,
      type: "sequence",
      elements,
      question: [nextElement],
      options,
      correct: 0,
      difficulty: "easy",
      description: t(
        "patternRecognitionTest.descriptions.sequence_alternating"
      ),
    };
  }
};

const generateMatrixPattern = (id) => {
  const shapes = ["circle", "square", "triangle", "diamond"];
  const colors = ["red", "blue", "green", "yellow", "purple"];
  const elements = [];
  let correctElement;
  const baseShape = shapes[Math.floor(Math.random() * shapes.length)];
  const selectedColors = colors.slice(0, 3);
  for (let row = 0; row < 3; row++) {
    for (let col = 0; col < 3; col++) {
      if (row === 2 && col === 2) continue;
      elements.push({
        shape: baseShape,
        color: selectedColors[(row + col) % selectedColors.length],
        size: "medium",
        filled: true,
      });
    }
  }
  const correctColor = selectedColors[(2 + 2) % selectedColors.length];
  correctElement = {
    shape: baseShape,
    color: correctColor,
    size: "medium",
    filled: true,
  };
  const description = t("patternRecognitionTest.descriptions.matrix");
  const otherShapes = shapes.filter((s) => s !== correctElement.shape);
  const otherColors = colors.filter((c) => c !== correctElement.color);
  const options = [
    [correctElement],
    [{ ...correctElement, color: otherColors[0] }],
    [{ ...correctElement, shape: otherShapes[0] }],
    [{ ...correctElement, filled: !correctElement.filled }],
  ];
  return {
    id,
    type: "matrix",
    elements,
    question: [correctElement],
    options,
    correct: 0,
    difficulty: "medium",
    description,
  };
};

const generateRotationPattern = (id) => {
  const shapes = ["triangle", "diamond", "star", "hexagon"];
  const colors = ["blue", "purple", "green", "red", "orange"];
  const shape = shapes[Math.floor(Math.random() * shapes.length)];
  const color = colors[Math.floor(Math.random() * colors.length)];
  let elements = [];
  let correctElement;
  for (let i = 0; i < 4; i++) {
    elements.push({
      shape,
      color,
      size: "medium",
      rotation: i * 90,
      filled: true,
    });
  }
  correctElement = { shape, color, size: "medium", rotation: 0, filled: true };
  const description = t("patternRecognitionTest.descriptions.rotation");
  const correctRotation = correctElement.rotation;
  const wrongRotations = [
    (correctRotation + 45) % 360,
    (correctRotation + 90) % 360,
    (correctRotation + 180) % 360,
  ];
  const options = [
    [correctElement],
    [
      {
        shape,
        color,
        size: "medium",
        rotation: wrongRotations[0],
        filled: true,
      },
    ],
    [
      {
        shape,
        color,
        size: "medium",
        rotation: wrongRotations[1],
        filled: true,
      },
    ],
    [
      {
        shape,
        color,
        size: "medium",
        rotation: wrongRotations[2],
        filled: true,
      },
    ],
  ];
  return {
    id,
    type: "rotation",
    elements,
    question: [correctElement],
    options,
    correct: 0,
    difficulty: "hard",
    description,
  };
};

const generateColorSequencePattern = (id) => {
  const shapes = ["circle", "square", "triangle", "diamond"];
  const shape = shapes[Math.floor(Math.random() * shapes.length)];
  const colors = ["red", "yellow", "green", "blue"];
  const elements = colors
    .slice(0, 3)
    .map((color) => ({ shape, color, size: "medium", filled: true }));
  const correctElement = {
    shape,
    color: colors[3],
    size: "medium",
    filled: true,
  };
  const description = t("patternRecognitionTest.descriptions.color_sequence");
  const allColors = [
    "red",
    "blue",
    "green",
    "yellow",
    "purple",
    "orange",
    "pink",
  ];
  const wrongColors = allColors
    .filter((c) => c !== correctElement.color)
    .slice(0, 3);
  const options = [
    [correctElement],
    [{ ...correctElement, color: wrongColors[0] }],
    [{ ...correctElement, color: wrongColors[1] }],
    [{ ...correctElement, color: wrongColors[2] }],
  ];
  return {
    id,
    type: "color_sequence",
    elements,
    question: [correctElement],
    options,
    correct: 0,
    difficulty: "easy",
    description,
  };
};

const generateSizeProgressionPattern = (id) => {
  const shapes = ["square", "circle", "triangle", "diamond"];
  const colors = ["purple", "blue", "green", "orange", "red"];
  const shape = shapes[Math.floor(Math.random() * shapes.length)];
  const color = colors[Math.floor(Math.random() * colors.length)];
  const elements = [
    { shape, color, size: "small", filled: true },
    { shape, color, size: "medium", filled: true },
    { shape, color, size: "large", filled: true },
  ];
  const correctElement = { shape, color, size: "large", filled: true };
  const description = t("patternRecognitionTest.descriptions.size_progression");
  const allSizes = ["small", "medium", "large"];
  const wrongSizes = allSizes.filter((s) => s !== correctElement.size);
  const options = [
    [correctElement],
    [{ shape, color, size: wrongSizes[0], filled: true }],
    [{ shape, color, size: wrongSizes[1], filled: true }],
    [
      {
        shape: shapes[(shapes.indexOf(shape) + 1) % shapes.length],
        color,
        size: correctElement.size,
        filled: true,
      },
    ],
  ];
  return {
    id,
    type: "size_progression",
    elements,
    question: [correctElement],
    options,
    correct: 0,
    difficulty: "medium",
    description,
  };
};

const generateShapePattern = (id) => {
  const colors = ["green", "blue", "purple", "red", "orange"];
  const color = colors[Math.floor(Math.random() * colors.length)];
  const shapes = ["circle", "triangle", "square", "hexagon"];
  const elements = shapes
    .slice(0, 3)
    .map((shape) => ({ shape, color, size: "medium", filled: true }));
  const correctElement = {
    shape: shapes[3],
    color,
    size: "medium",
    filled: true,
  };
  const options = [
    [correctElement],
    [{ shape: "star", color, size: "medium", filled: true }],
    [{ shape: "diamond", color, size: "medium", filled: true }],
    [{ shape: shapes[0], color, size: "medium", filled: true }],
  ];
  return {
    id,
    type: "shape_pattern",
    elements,
    question: [correctElement],
    options,
    correct: 0,
    difficulty: "hard",
    description: t("patternRecognitionTest.descriptions.shape_pattern"),
  };
};

const generateComplexPattern = (id) => {
  const shapes = ["circle", "square", "triangle", "diamond"];
  const colors = ["red", "blue", "green", "yellow"];
  const sizes = ["small", "medium", "large"];
  const elements = [
    { shape: shapes[0], color: colors[0], size: sizes[0], filled: true },
    { shape: shapes[1], color: colors[1], size: sizes[1], filled: true },
    { shape: shapes[2], color: colors[2], size: sizes[2], filled: true },
  ];
  const correctElement = {
    shape: shapes[3],
    color: colors[3] || colors[0],
    size: sizes[0],
    filled: true,
  };
  const options = [
    [correctElement],
    [{ shape: shapes[3], color: colors[0], size: sizes[2], filled: true }],
    [
      {
        shape: shapes[0],
        color: colors[3] || colors[0],
        size: sizes[0],
        filled: true,
      },
    ],
    [{ shape: shapes[2], color: colors[2], size: sizes[1], filled: true }],
  ];
  return {
    id,
    type: "sequence",
    elements,
    question: [correctElement],
    options,
    correct: 0,
    difficulty: "hard",
    description: t("patternRecognitionTest.descriptions.complex"),
  };
};

let timerInterval;
watch([stage, timeLeft], () => {
  if (stage.value === "test" && timeLeft.value > 0) {
    if (!timerInterval) {
      timerInterval = setInterval(() => {
        if (timeLeft.value <= 1) {
          stage.value = "results";
          timeLeft.value = 0;
          clearInterval(timerInterval);
          timerInterval = null;
        } else {
          timeLeft.value -= 1;
        }
      }, 1000);
    }
  } else {
    if (timerInterval) {
      clearInterval(timerInterval);
      timerInterval = null;
    }
  }
});

onUnmounted(() => {
  if (timerInterval) {
    clearInterval(timerInterval);
  }
});

const handleStartTest = () => {
  patterns.value = generatePatterns();
  stage.value = "test";
  startTime.value = Date.now();
};

const handleAnswer = (answerIndex) => {
  const pattern = patterns.value[currentPattern.value];
  const correct = answerIndex === pattern.correct;

  responses.value.push(answerIndex);

  if (correct) {
    score.value += 1;
  }

  feedbackCorrect.value = correct;
  showFeedback.value = true;

  setTimeout(
    () => {
      showFeedback.value = false;
      if (currentPattern.value < patterns.value.length - 1) {
        currentPattern.value += 1;
      } else {
        stage.value = "results";
      }
    },
    correct ? 1500 : 2500
  );
};

const handleComplete = () => {
  const totalPatterns = patterns.value.length;
  const correctAnswers = score.value;
  const accuracy = Math.round((correctAnswers / totalPatterns) * 100);
  const timeUsed = Math.round((Date.now() - startTime.value) / 1000);

  const result = {
    id: Date.now().toString(),
    testType: t("patternRecognitionTest.title"),
    score: accuracy,
    details: `准确率 ${accuracy}%, 完成 ${totalPatterns} 题, 平均每题 ${Math.round(
      timeUsed / totalPatterns
    )} 秒`,
    timestamp: new Date(),
  };

  if (props.onComplete) {
    props.onComplete(result);
  }
};

const resetTest = () => {
  stage.value = "instructions";
  currentPattern.value = 0;
  patterns.value = [];
  responses.value = [];
  score.value = 0;
  showFeedback.value = false;
  timeLeft.value = 600;
};

const getRating = () => {
  const accuracy = Math.round((score.value / patterns.value.length) * 100);
  if (accuracy >= 90)
    return {
      text: t("patternRecognitionTest.results.ratings.master"),
      color: "text-yellow-500",
    };
  if (accuracy >= 80)
    return {
      text: t("patternRecognitionTest.results.ratings.excellent"),
      color: "text-green-500",
    };
  if (accuracy >= 70)
    return {
      text: t("patternRecognitionTest.results.ratings.good"),
      color: "text-blue-500",
    };
  if (accuracy >= 60)
    return {
      text: t("patternRecognitionTest.results.ratings.average"),
      color: "text-gray-500",
    };
  return {
    text: t("patternRecognitionTest.results.ratings.needsImprovement"),
    color: "text-orange-500",
  };
};
</script>

<template>
  <div v-if="stage === 'instructions'" class="max-w-2xl mx-auto">
    <Card class="bg-white/90 backdrop-blur-sm border-orange-200 shadow-lg">
      <CardHeader class="text-center pb-8">
        <div
          class="w-16 h-16 bg-gradient-to-br from-orange-600 to-red-500 rounded-2xl flex items-center justify-center mx-auto mb-4 shadow-lg"
        >
          <Boxes class="w-8 h-8 text-white" />
        </div>
        <CardTitle class="text-2xl text-slate-800">{{
          t("patternRecognitionTest.title")
        }}</CardTitle>
        <p class="text-slate-600 mt-2">
          {{ t("patternRecognitionTest.description") }}
        </p>
      </CardHeader>

      <CardContent class="space-y-6">
        <div
          class="bg-gradient-to-r from-orange-50 to-red-50 rounded-xl p-6 border border-orange-100"
        >
          <h3
            class="font-semibold text-orange-900 mb-4 flex items-center gap-2"
          >
            <Star class="w-5 h-5" />
            {{ t("patternRecognitionTest.instructions.title") }}
          </h3>
          <div class="space-y-3 text-slate-700">
            <div class="flex gap-3">
              <span
                class="w-6 h-6 bg-orange-600 text-white rounded-full flex items-center justify-center text-sm font-semibold flex-shrink-0 mt-0.5"
                >1</span
              >
              <p>{{ t("patternRecognitionTest.instructions.step1") }}</p>
            </div>
            <div class="flex gap-3">
              <span
                class="w-6 h-6 bg-orange-600 text-white rounded-full flex items-center justify-center text-sm font-semibold flex-shrink-0 mt-0.5"
                >2</span
              >
              <p>{{ t("patternRecognitionTest.instructions.step2") }}</p>
            </div>
            <div class="flex gap-3">
              <span
                class="w-6 h-6 bg-orange-600 text-white rounded-full flex items-center justify-center text-sm font-semibold flex-shrink-0 mt-0.5"
                >3</span
              >
              <p>{{ t("patternRecognitionTest.instructions.step3") }}</p>
            </div>
            <div class="flex gap-3">
              <span
                class="w-6 h-6 bg-orange-600 text-white rounded-full flex items-center justify-center text-sm font-semibold flex-shrink-0 mt-0.5"
                >4</span
              >
              <p>{{ t("patternRecognitionTest.instructions.step4") }}</p>
            </div>
          </div>
        </div>

        <div class="grid md:grid-cols-2 gap-4">
          <div
            class="bg-gradient-to-br from-blue-50 to-blue-100 rounded-xl p-4 border border-blue-200"
          >
            <h4 class="font-semibold text-blue-800 mb-2">
              {{ t("patternRecognitionTest.features.sequence.title") }}
            </h4>
            <p class="text-sm text-blue-700">
              {{ t("patternRecognitionTest.features.sequence.description") }}
            </p>
          </div>
          <div
            class="bg-gradient-to-br from-green-50 to-green-100 rounded-xl p-4 border border-green-200"
          >
            <h4 class="font-semibold text-green-800 mb-2">
              {{ t("patternRecognitionTest.features.matrix.title") }}
            </h4>
            <p class="text-sm text-green-700">
              {{ t("patternRecognitionTest.features.matrix.description") }}
            </p>
          </div>
        </div>

        <div class="grid md:grid-cols-3 gap-4">
          <div
            class="text-center p-4 bg-gradient-to-br from-orange-50 to-orange-100 rounded-xl border border-orange-200"
          >
            <div class="text-2xl font-bold text-orange-600 mb-1">6</div>
            <div class="text-sm text-orange-700">
              {{ t("patternRecognitionTest.summary.types") }}
            </div>
          </div>
          <div
            class="text-center p-4 bg-gradient-to-br from-red-50 to-red-100 rounded-xl border border-red-200"
          >
            <div class="text-2xl font-bold text-red-600 mb-1">15</div>
            <div class="text-sm text-red-700">
              {{ t("patternRecognitionTest.summary.questions") }}
            </div>
          </div>
          <div
            class="text-center p-4 bg-gradient-to-br from-orange-50 to-red-50 rounded-xl border border-orange-200"
          >
            <div class="text-2xl font-bold text-slate-600 mb-1">10</div>
            <div class="text-sm text-slate-700">
              {{ t("patternRecognitionTest.summary.timeLimit") }}
            </div>
          </div>
        </div>

        <Button
          @click="handleStartTest"
          class="w-full bg-gradient-to-r from-slate-400 to-gray-500 hover:from-slate-500 hover:to-gray-600 text-white shadow-lg hover:shadow-xl transform hover:scale-105 transition-all duration-300 border-0 min-w-[140px] h-12"
          size="lg"
        >
          {{ t("patternRecognitionTest.startTest") }}
        </Button>
      </CardContent>
    </Card>
  </div>

  <div
    v-else-if="stage === 'test' && patterns.length > 0"
    class="max-w-4xl mx-auto space-y-6"
  >
    <div class="flex flex-col sm:flex-row gap-4 items-center justify-between">
      <div class="flex items-center gap-4">
        <Badge
          variant="outline"
          class="bg-orange-100 text-orange-700 border-orange-300"
        >
          {{
            t("patternRecognitionTest.test.progress", {
              current: currentPattern + 1,
              total: patterns.length,
            })
          }}
        </Badge>
        <Badge
          variant="outline"
          :class="{
            'bg-blue-100 text-blue-700 border-blue-300':
              patterns[currentPattern].type === 'sequence',
            'bg-green-100 text-green-700 border-green-300':
              patterns[currentPattern].type === 'matrix',
            'bg-purple-100 text-purple-700 border-purple-300':
              patterns[currentPattern].type === 'rotation',
            'bg-yellow-100 text-yellow-700 border-yellow-300':
              patterns[currentPattern].type === 'color_sequence',
            'bg-pink-100 text-pink-700 border-pink-300':
              patterns[currentPattern].type === 'size_progression',
            'bg-indigo-100 text-indigo-700 border-indigo-300':
              patterns[currentPattern].type === 'shape_pattern',
          }"
        >
          {{
            t(
              `patternRecognitionTest.test.patternTypes.${patterns[currentPattern].type}`
            )
          }}
        </Badge>
        <div class="flex items-center gap-2 text-slate-600">
          <Trophy class="w-4 h-4" />
          <span class="font-semibold">{{ score }}</span>
        </div>
      </div>

      <div class="flex items-center gap-2">
        <Clock class="w-4 h-4 text-slate-500" />
        <span
          :class="[
            'font-mono text-lg font-bold',
            timeLeft <= 60 ? 'text-red-500' : 'text-slate-700',
          ]"
        >
          {{ Math.floor(timeLeft / 60) }}:{{
            (timeLeft % 60).toString().padStart(2, "0")
          }}
        </span>
      </div>
    </div>

    <Progress
      :modelValue="((currentPattern + 1) / patterns.length) * 100"
      class="h-2"
    />

    <Card class="bg-white/90 backdrop-blur-sm border-orange-200 shadow-lg">
      <CardHeader>
        <CardTitle class="text-lg text-slate-800">{{
          patterns[currentPattern].description
        }}</CardTitle>
      </CardHeader>
      <CardContent class="space-y-6">
        <div class="bg-slate-50 rounded-lg p-6">
          <h4 class="text-md font-semibold text-slate-700 mb-4">
            {{ t("patternRecognitionTest.test.observe") }}
          </h4>
          <div
            :class="[
              'flex items-center justify-center gap-4',
              {
                'grid grid-cols-3 gap-6 max-w-sm mx-auto':
                  patterns[currentPattern].type === 'matrix',
                'flex items-end gap-8':
                  patterns[currentPattern].type === 'size_progression',
                'flex-wrap':
                  patterns[currentPattern].type !== 'matrix' &&
                  patterns[currentPattern].type !== 'size_progression',
              },
            ]"
          >
            <div
              v-for="(element, index) in patterns[currentPattern].elements"
              :key="index"
              :class="[
                'flex items-center justify-center p-3',
                patterns[currentPattern].type === 'size_progression'
                  ? 'min-h-[120px] min-w-[120px]'
                  : 'min-h-[60px] min-w-[60px]',
              ]"
            >
              <ShapeRenderer
                :element="element"
                :baseSize="
                  patterns[currentPattern].type === 'size_progression' ? 80 : 50
                "
              />
            </div>
            <div
              v-if="patterns[currentPattern].type === 'matrix'"
              class="flex items-center justify-center p-2 border-2 border-dashed border-slate-300 rounded bg-white min-h-[60px] min-w-[60px]"
            >
              <span class="text-2xl text-slate-400">?</span>
            </div>
            <div
              v-else
              :class="[
                'flex items-center justify-center p-3',
                patterns[currentPattern].type === 'size_progression'
                  ? 'min-h-[120px] min-w-[120px]'
                  : 'min-h-[60px] min-w-[60px]',
              ]"
            >
              <span class="text-2xl text-slate-400">→ ?</span>
            </div>
          </div>
          <div
            v-if="patterns[currentPattern].type === 'size_progression'"
            class="mt-6 text-center"
          >
            <p class="text-sm text-slate-600 font-medium">
              {{ t("patternRecognitionTest.test.sizeProgression.observe") }}
            </p>
            <p class="text-xs text-slate-500 mt-1">
              {{ t("patternRecognitionTest.test.sizeProgression.description") }}
            </p>
          </div>
        </div>

        <div>
          <h4 class="text-md font-semibold text-slate-700 mb-4">
            {{ t("patternRecognitionTest.test.selectAnswer") }}
          </h4>
          <div
            :class="[
              'grid',
              patterns[currentPattern].type === 'size_progression'
                ? 'grid-cols-2 sm:grid-cols-4 gap-6'
                : 'grid-cols-2 sm:grid-cols-4 gap-4',
            ]"
          >
            <div
              v-for="(option, index) in patterns[currentPattern].options"
              :key="index"
            >
              <Button
                variant="outline"
                @click="handleAnswer(index)"
                :disabled="showFeedback"
                :class="[
                  'w-full transition-all duration-300 flex items-center justify-center',
                  patterns[currentPattern].type === 'size_progression'
                    ? 'h-40 p-6'
                    : 'h-28 p-4',
                  showFeedback && index === patterns[currentPattern].correct
                    ? 'bg-green-500 text-white border-green-500 hover:bg-green-600'
                    : 'hover:bg-orange-50 hover:border-orange-300',
                ]"
              >
                <div
                  :class="[
                    'flex items-center justify-center',
                    patterns[currentPattern].type === 'size_progression'
                      ? 'min-h-[120px] min-w-[120px]'
                      : 'min-h-[60px] min-w-[60px]',
                  ]"
                >
                  <template v-if="option && option.length > 0">
                    <div
                      v-for="(element, elemIndex) in option"
                      :key="elemIndex"
                      class="flex items-center justify-center"
                    >
                      <ShapeRenderer
                        :element="element"
                        :baseSize="
                          patterns[currentPattern].type === 'size_progression'
                            ? 85
                            : 52
                        "
                      />
                    </div>
                  </template>
                  <div
                    v-else
                    class="w-12 h-12 bg-slate-100 border border-slate-300 rounded flex items-center justify-center text-slate-400"
                  >
                    ?
                  </div>
                </div>
              </Button>
            </div>
          </div>
          <div
            v-if="patterns[currentPattern].type === 'size_progression'"
            class="mt-4 text-center"
          >
            <p class="text-xs text-slate-500">
              {{ t("patternRecognitionTest.test.sizeProgression.tip") }}
            </p>
          </div>
        </div>

        <Transition name="fade">
          <div
            v-if="showFeedback"
            :class="[
              'text-center p-4 rounded-lg',
              feedbackCorrect
                ? 'bg-green-50 text-green-700 border border-green-200'
                : 'bg-red-50 text-red-700 border border-red-200',
            ]"
          >
            <div class="flex items-center justify-center gap-2 mb-2">
              <span class="text-2xl">{{ feedbackCorrect ? "✅" : "❌" }}</span>
              <span class="font-semibold">{{
                feedbackCorrect
                  ? t("patternRecognitionTest.feedback.correct")
                  : t("patternRecognitionTest.feedback.incorrect")
              }}</span>
            </div>
            <div v-if="!feedbackCorrect" class="text-sm">
              {{ t("patternRecognitionTest.feedback.correctAnswerIs")
              }}<span class="font-semibold text-green-600">{{
                t("patternRecognitionTest.feedback.colorGreen")
              }}</span
              >{{ t("patternRecognitionTest.feedback.marked") }}
            </div>
          </div>
        </Transition>
      </CardContent>
    </Card>
  </div>

  <div v-else-if="stage === 'results'" class="max-w-2xl mx-auto space-y-6">
    <Card>
      <CardHeader class="text-center">
        <CardTitle class="flex items-center justify-center gap-2">
          <CheckCircle class="w-6 h-6 text-orange-500" />
          {{ t("patternRecognitionTest.results.title") }}
        </CardTitle>
      </CardHeader>
      <CardContent class="space-y-6">
        <div class="text-center space-y-4">
          <div class="text-6xl font-bold text-primary">
            {{ Math.round((score / patterns.length) * 100) }}
          </div>
          <div :class="['text-xl font-semibold', getRating().color]">
            {{ getRating().text }}
          </div>
        </div>

        <div class="grid grid-cols-2 md:grid-cols-4 gap-4">
          <div class="text-center p-4 bg-green-50 dark:bg-green-950 rounded-lg">
            <div class="text-2xl font-bold text-green-600">{{ score }}</div>
            <div class="text-sm text-muted-foreground">
              {{ t("patternRecognitionTest.results.correct") }}
            </div>
          </div>
          <div class="text-center p-4 bg-red-50 dark:bg-red-950 rounded-lg">
            <div class="text-2xl font-bold text-red-600">
              {{ patterns.length - score }}
            </div>
            <div class="text-sm text-muted-foreground">
              {{ t("patternRecognitionTest.results.incorrect") }}
            </div>
          </div>
          <div class="text-center p-4 bg-blue-50 dark:bg-blue-950 rounded-lg">
            <div class="text-2xl font-bold text-blue-600">
              {{ Math.round((score / patterns.length) * 100) }}%
            </div>
            <div class="text-sm text-muted-foreground">
              {{ t("patternRecognitionTest.results.accuracy") }}
            </div>
          </div>
          <div
            class="text-center p-4 bg-purple-50 dark:bg-purple-950 rounded-lg"
          >
            <div class="text-2xl font-bold text-purple-600">
              {{ patterns.length }}
            </div>
            <div class="text-sm text-muted-foreground">
              {{ t("patternRecognitionTest.results.totalQuestions") }}
            </div>
          </div>
        </div>

        <div class="space-y-2">
          <h3 class="font-semibold">
            {{ t("patternRecognitionTest.results.analysisTitle") }}
          </h3>
          <div class="text-sm text-muted-foreground space-y-1">
            <p>
              {{
                t("patternRecognitionTest.results.analysis.line1", {
                  count: patterns.length,
                })
              }}
            </p>
            <p>{{ t("patternRecognitionTest.results.analysis.line2") }}</p>
            <p>
              {{
                t("patternRecognitionTest.results.analysis.line3", {
                  time: Math.round(
                    (Date.now() - startTime) / 1000 / patterns.length
                  ),
                })
              }}
            </p>
            <p
              v-if="Math.round((score / patterns.length) * 100) >= 85"
              class="text-green-600"
            >
              {{ t("patternRecognitionTest.results.analysis.ratingExcellent") }}
            </p>
            <p
              v-if="Math.round((score / patterns.length) * 100) < 70"
              class="text-orange-600"
            >
              {{
                t("patternRecognitionTest.results.analysis.ratingSuggestion")
              }}
            </p>
          </div>
        </div>

        <div class="flex gap-4">
          <Button
            @click="resetTest"
            variant="outline"
            class="flex-1 border-2 border-slate-300 hover:border-slate-400 hover:bg-slate-50 text-slate-700 hover:text-slate-800 shadow-sm hover:shadow-md transition-all duration-300"
          >
            <RotateCcw class="w-4 h-4 mr-2" />
            {{ t("patternRecognitionTest.results.restartButton") }}
          </Button>
          <Button
            @click="handleComplete"
            class="flex-1 bg-gradient-to-r from-orange-500 to-red-600 hover:from-orange-600 hover:to-red-700 text-white shadow-lg hover:shadow-xl transform hover:scale-105 transition-all duration-300 border-0"
          >
            <CheckCircle class="w-4 h-4 mr-2" />
            {{ t("patternRecognitionTest.results.saveButton") }}
          </Button>
        </div>
      </CardContent>
    </Card>
  </div>
</template>

<style scoped>
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.5s ease;
}
.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}
</style>
